/*
 *
 * Copyright (C) 2012 Mauricio Garcia
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "administration.h"

const int MAXPEERS = 31;
char connectKey[64] = "-c";
int connectKeyLen = 2;
char disconnectKey[64] = "-d";
int disconnectKeyLen = 2;
char establishedKey[64] = "-e";
int establishedKeyLen = 2;
char unestablishedKey[64] = "-u";
int unestablishedKeyLen = 2;

// Insert in the hash table
int insertPeer(struct nodeList *sockList[], int peer,
	       struct sockaddr_in* sockaddr, char id[]){
  int k = peer%MAXPEERS;
  struct nodeList *tmp = sockList[k];
  sockList[k] = (struct nodeList*)malloc(sizeof(struct nodeList));
  if(sockList[k] == NULL) return -1;
  sockList[k]->key.peer = peer;
  sockList[k]->key.addr = *sockaddr;
  sockList[k]->key.peerOther = -1;
  sockList[k]->key.lenID = strlen(id);
  strcpy(sockList[k]->key.id,id);
  sockList[k]->next = tmp;
  return 1;
}

// Get from the hash table
struct peer* getPeer(struct nodeList *sockList[], int peer){
  int k = peer%MAXPEERS;

  struct nodeList *tmp = sockList[k];
  while(tmp != NULL){
    if(tmp->key.peer == peer){
      return &tmp->key;
    }
    tmp = tmp->next;
  }
  return NULL;
}

// Remove from the hash table
int removePeer(struct nodeList *sockList[], int peer){
  int k = peer%MAXPEERS;
  if(sockList[k] == NULL) return -1;
  if(sockList[k]->key.peer == peer){
    free(sockList[k]);
    sockList[k] = NULL;
    return 1;
  }
  struct nodeList *prev = sockList[k];
  struct nodeList *tmp = prev->next;
  while(tmp != NULL){
    if(tmp->key.peer == peer){
      prev->next = tmp->next;
      free(tmp);
      break;
    }
    prev = prev->next;
    tmp = prev->next;
  }
  return 1;
}

// Free the memory of a list
void freeList(struct nodeList **node){
  if((*node) == NULL) return;
	freeList(&(*node)->next);
	if((*node)) free((*node));
}
